/**
 * 获取代理的地区
 */

var Q = require("q"),
    request = require("request"),
    zlib = require("zlib"),
    Util = require("../util/util.js"),
    App = require("../common/App.js");

module.exports = new ProxyRegion();

function ProxyRegion(){
    this.resBodyTimeout = 5000;//响应设置超时时间
    this.resBodyMd5 = 'd8400ed485cf9d98bfe5c60e398eac19';
    this.resBodyOptions = {
        proxy:"http://localhost:8080",
        url:'http://www.baidu.com/s?wd=男科',
        timeout:this.resBodyTimeout,
        encoding:null,
        headers:{
            'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Charset':'GBK,utf-8;q=0.7,*;q=0.3',
            'Accept-Encoding':'gzip',
            'Accept-Language':'zh-CN,zh;q=0.8',
            'Cache-Control':'max-age=0',
            'Connection':'keep-alive',
            'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11'
            //'Cookie':'BAIDUID=08CFA6D95994B1CBD5B119284AD08950:FG=1'
        }
    };
}


ProxyRegion.prototype.start = function(proxy){
    var deferred = Q.defer();
    var that = this;

    var regionSuccess = function(region){
        if(!isNaN(region.regionId)){
            deferred.reject(new Error("Region Not Found"));
        }
        proxy.regionId = region.id;
        proxy.region = region.name;

        deferred.resolve(proxy);
    }

    //没有地区缓存调用的方法
    var notRegionCache = function(){
        that.reqBaidu(proxy) //先到百度搜索关键词 "男科" 返回搜索结果
        .then(
            function(buffer_body){
                return buffer_body.toString();
            }
        )
        .then(
            function(body){
                return that.analysisRegion(body);
            }
        )
        .then(
            function(region){
                //设置缓存
                that.setRegionCache(proxy,region);

                regionSuccess(region);
            },
            function(err){
                deferred.reject(err);
            }
        );
    }
    notRegionCache();

    /*
    this.getRegionCache(proxy).then(
        function(region){
            if(!isNaN(region.id)){
                regionSuccess(region);
            }else{
                notRegionCache();
            }
        },
        function(){
            notRegionCache();
        }
    )
    */

    return deferred.promise;
}


/**
 * 从缓存服务器中获取缓存
 * @param proxy
 * @returns {*}
 */
ProxyRegion.prototype.getRegionCache = function(proxy){
    var deferred = Q.defer();
    var url = App.config.region.getcache_url+"?host="+proxy.host+"&port="+proxy.port;
	console.log(url);
    request.get(url,function(err,res,body){
        if(err){
            deferred.reject(err);
        }else if(res.statusCode!=200){
            deferred.reject(new Error("getRegionCache http status "+res.statusCode));
        }else{
            try{
                deferred.resolve(JSON.parse(body));
            }catch (e){
                deferred.reject(e);
            }
        }
    })
    return deferred.promise;
}

/**
 * 从缓存服务器中获取缓存
 * @param proxy
 * @returns {*}
 */
ProxyRegion.prototype.setRegionCache = function(proxy,region){
    var deferred = Q.defer();
    var url = App.config.region.setcache_url+"?host="+proxy.host+"&port="+proxy.port+"&region="+JSON.stringify(region);
    request.get(url,function(err,res,body){
        if(err){
            deferred.reject(err);
        }else if(res.statusCode!=200){
            deferred.reject(new Error("setRegionCache http status "+res.statusCode));
        }else{
            if(body=="sucess"){
                deferred.resolve();
            }else{
                deferred.reject(new Error("setRegionCache "+body));
            }
        }
    })
    return deferred.promise;
}

/**
 * 发起解析地区的请求
 * @param body
 * @returns {*}
 */
ProxyRegion.prototype.analysisRegion= function(body){
    var deferred = Q.defer();
    var that = this;
    request(
        {
            method: 'POST',
            uri: App.config.region.parse_region_url,
            form :{body:body}
        },
        function (error, res, body) {
            if(error){
                deferred.reject(error);
            }else if(res.statusCode!=200){
                deferred.reject(new Error("http status "+res.statusCode));
            }else{
                try{
                    deferred.resolve(JSON.parse(body));
                }catch (e){
                    deferred.reject(e);
                }
            }
        }
    )
    return deferred.promise;
}

ProxyRegion.prototype.reqBaidu= function(proxy){
    var deferred = Q.defer();
    var that = this;
    var BAIDUID = Util.md5((new Date()).getTime().toString()).toUpperCase();
    var resBodyOptions = this.resBodyOptions;
    //resBodyOptions.headers.cookie = "BAIDUID:"+BAIDUID+":FG=1";
    resBodyOptions.proxy = "http://"+proxy.host+":"+proxy.port;
    var dateS1 = new Date();

    var req = request.get(resBodyOptions,function(err, res, buffer_body){
        if(err){
            deferred.reject(err);
            return ;
        }
        if(res.statusCode == 200){
            var dateS2 = new Date();
            proxy.resBaiduTime = dateS2-dateS1;
            if(res.headers['content-encoding']=="gzip"){
                zlib.gunzip(buffer_body,function(err,body){
                    if(!err){
                        deferred.resolve(body);
                    }else{
                        deferred.reject(err);
                    }
                });
            }else{
                deferred.resolve(buffer_body);
            }
        }else{
            deferred.reject(new Error("baidu http status "+res.statusCode));
        }
    });

    return deferred.promise;
}

